import { CharacterState, CharacterDir, NpcDat } from '../Tools/QType';
import ScriptManager from '../Tools/ScriptManager';
import Character from './Basis/Character';
import QGame from '../Tools/QGame';
const {ccclass, property} = cc._decorator;

@ccclass
export default class Player extends Character {
    isLeader:boolean = false;
    
    /** 跟班 */
    pensioner:Player


    /**
     * 人物所在的地形坐标
     */
    _terrainPositon:cc.Vec2;
    get terrainPosition(){
        return this._terrainPositon;
    }
    set terrainPosition(value){
        if(this._terrainPositon==value)return;                  
        this._terrainPositon = value;                       
    }
    
    pensionerPaths:cc.Vec2[] = [];

    onLoad(){
        super.onLoad();
    
        this.node.setAnchorPoint(0.5,0);     
        this.sprite.spriteFrame = null;
     
        //加载相关素材
        cc.loader.loadRes("Character/"+this.dat.code,cc.SpriteAtlas,(err,atlas)=>{            
            this.init(atlas)
        })
        
        this.node.on("position-changed",this.computeTerrainPostion,this);
    }

    setDat(dat){      
        super.setDat(dat)        
    }

    /**
     * 初始化角色
     * 前4张为四方向图
     * 后为行走图
     */
    init(atlas:cc.SpriteAtlas){
        let sps = atlas.getSpriteFrames();
        sps.sort( (a,b)=>{
            return Number(a.name)-Number(b.name)
        })        
        let dirSp = sps.splice(0,4);
        for(let i=0;i<4;i++){
            let tempSp = dirSp[i];
            let clip = cc.AnimationClip.createWithSpriteFrames([tempSp],1);
            clip.wrapMode = cc.WrapMode.Default;
            clip.name = CharacterState.Idle+"_"+i;
            this.animation.addClip(clip);
        }


        let n = sps.length/4;
        for(let i=0;i<4;i++){
            let tempSp = sps.splice(0,n) as [cc.SpriteFrame];
            let clip = cc.AnimationClip.createWithSpriteFrames(tempSp,n);
            clip.wrapMode = cc.WrapMode.Loop;
            clip.name = CharacterState.Move+"_"+i.toString();
            this.animation.addClip(clip);
        }                
        this.playAnim()        
    }

    start(){   
      
    }

 
    update(dt){
        this.node.setSiblingIndex(240+this.node.y);     
        if(this.isLeader){
            switch(this.state){
                case CharacterState.Idle:
                break;
                case CharacterState.Move:                
                    this.move(dt);
                break;
                case CharacterState.Speak:
                break;
            }        
        }       
    }

    /**
     * 计算人物所在的地形坐标
     */
    computeTerrainPostion(){
        let v2 = ScriptManager.Instance.MapTerrain.getTileV2(this.node.position);
        this.terrainPosition = v2;
    }
   


}
